using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using XUCore.Ddd.Domain;
using XUCore.NetCore.FreeSql.Entity;

namespace XUCore.NetCore.FreeSql.Curd
{
    /// <summary>
    /// CURD服务
    /// </summary>
    /// <typeparam name="TKey">主键类型</typeparam>
    /// <typeparam name="TUkey">用户主键类型</typeparam>
    /// <typeparam name="TEntity">数据库实体</typeparam>
    /// <typeparam name="TDto">返回实体</typeparam>
    /// <typeparam name="TCreateCommand">创建命令</typeparam>
    /// <typeparam name="TUpdateCommand">修改命令</typeparam>
    /// <typeparam name="TQueryCommand">查询命令</typeparam>
    /// <typeparam name="TQueryPageCommand">查询分页命令</typeparam>
    public abstract class CurdService<TKey, TUkey, TEntity, TDto, TCreateCommand, TUpdateCommand, TQueryCommand, TQueryPageCommand> :
        CurdService<TKey, TUkey, TEntity, TDto, TCreateCommand, TUpdateCommand, TQueryPageCommand>,
        ICurdService<TKey, TUkey, TEntity, TDto, TCreateCommand, TUpdateCommand, TQueryCommand, TQueryPageCommand>
            where TEntity : EntityFull<TKey, TUkey>, new()
            where TDto : class, new()
            where TCreateCommand : CreateCommand
            where TUpdateCommand : UpdateCommand<TKey>
            where TQueryCommand : ListCommand
            where TQueryPageCommand : PageCommand
    {
        /// <summary>
        /// CURD服务
        /// </summary>
        /// <param name="freeSql"></param>
        /// <param name="mapper"></param>
        public CurdService(IFreeSql freeSql, IMapper mapper) : base(freeSql, mapper) { }

        /// <summary>
        /// 查询列表
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public virtual async Task<List<TDto>> GetListAsync([FromQuery] TQueryCommand request, CancellationToken cancellationToken = default)
        {
            var res = await repo.Select
                .LimitIf(request.Limit > 0, request.Limit)
                .OrderByDescending(c => c.CreatedAt)
                .ToListAsync(cancellationToken);

            return mapper.Map<List<TDto>>(res);
        }
    }
}